
// console.dir(Vue)
let _Vue = null
class VueRouter {
    static install(Vue){
        if(VueRouter.install.installed){
            return false
        }
        _Vue = Vue

        _Vue.mixin({
            beforeCreate(){
                if(this.$options.router){
                    _Vue.prototype.$router = this.$options.router    
                    
                }
            }
        })
    }

    constructor(options){
        this.options = options
        this.data = _Vue.observable({
            current:'#/'
        })
        this.routerMap = {}
        this.init()
    }

    init(){
        this.data.current = window.location.hash  
        this.createRouteMap()
        this.initComponents(_Vue)
        this.initEvent()
    }

    createRouteMap(){
        this.options.routes.forEach((route)=>{
            this.routerMap['#'+route.path] = route.component
        })
    }

    initComponents(){
        const self = this

        _Vue.component('router-link' , {
            props:{
                to:String
            },
            render(h){
                return h('a',{
                    attrs:{
                        href:this.to
                    },
                    on:{
                        click:this.handleClick
                    }
                },[this.$slots.default])
            },
            methods:{
                handleClick(e){
                    e.preventDefault()
                    // history.pushState({},"",this.to)
                    location.hash = this.to;
                    self.data.current = this.to                    
                }
            }
        })
        
        _Vue.component('router-view' , {
            render(h){
                console.log(self.data.current)
                let component = self.routerMap[self.data.current]
                return h(component)
            }
        })
    }

    initEvent(){
        window.addEventListener('hashchange' , ()=>{
            console.log(window.location.hash)
            this.data.current = window.location.hash
        })
    }
}
export default VueRouter